package com.android.activity;

import java.util.Set;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class ListActivity extends Activity {
    private BluetoothAdapter mBluetoothAdapter = null;
    private ArrayAdapter<String> mLista;
    private static final String TAG = "RCS_lista";
    private static final boolean DEBUG = true;
    public static String DIRECCION="direccion";

    protected void onCreate(Bundle padre) {
        super.onCreate(padre);
        if (DEBUG) Log.d(TAG, "onCreate ");
        setResult(Activity.RESULT_CANCELED);//Inicializacion.
        setContentView(R.layout.list);//Ventana Lista dispositivos.
        Button boton = (Button) findViewById(R.id.lista_boton);//Boton buscar.
        boton.setOnClickListener(new OnClickListener(){
        	public void onClick(View v){
        	v.setVisibility(View.GONE);
        	buscaDispositivos();
        	}
        	
        });
        if (DEBUG) Log.d(TAG, "onCreate - ArrayAdapter ");
        mLista = new ArrayAdapter<String>(this,R.layout.list_element);
        if (DEBUG) Log.d(TAG, "onCreate - find id.lista ");
        ListView lvLista = (ListView)findViewById(R.id.lista);
        if (DEBUG) Log.d(TAG, "onCreate - setAdapter ");
        lvLista.setAdapter(mLista);
        if (DEBUG) Log.d(TAG, "onCreate - setOnItemClickListener ");
        lvLista.setOnItemClickListener(mListaClickListener);
        if (DEBUG) Log.d(TAG, "onCreate - IntentFilter ");
        IntentFilter iFd = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mBroadcastReceiver, iFd);
        IntentFilter iFa = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(mBroadcastReceiver, iFa);
        if (DEBUG) Log.d(TAG, "onCreate - getDefaultAdapter ");
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (DEBUG) Log.d(TAG, "onCreate - fin ");
}
    //
    private void buscaDispositivos(){
		if (DEBUG)
			Log.d(TAG, "buscaDispositivos - ");
		if (mBluetoothAdapter.isDiscovering()) {
			if (DEBUG)
				Log.d(TAG, "buscaDispositivos - Estaba buscando, lo paro");
			mBluetoothAdapter.cancelDiscovery();
		} else {
			if (DEBUG)
				Log.d(TAG, "buscaDispositivos - No estaba buscando, continuo");
		}
		 Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

	        // If there are paired devices, add each one to the ArrayAdapter
	        if (pairedDevices.size() > 0) { 
	            for (BluetoothDevice device : pairedDevices) {
	                mLista.add(device.getName() + "\n" + device.getAddress());
	            }
		
	        }
		if (DEBUG)
			Log.d(TAG, "buscaDispositivos - startDiscovery");
		mBluetoothAdapter.startDiscovery();
    }
    private OnItemClickListener mListaClickListener = new OnItemClickListener(){
    	public void onItemClick(AdapterView<?> a, View v, int i, long l){
    		String cadenaDireccion = ((TextView)v).getText().toString();
    		if (DEBUG) Log.d(TAG, "onItemClick"+cadenaDireccion);
    		String direccion = cadenaDireccion.substring(cadenaDireccion.length()-17);
    		mBluetoothAdapter.cancelDiscovery();
    		Intent itnt = new Intent();
    		itnt.putExtra(DIRECCION, direccion);
    		setResult(Activity.RESULT_OK,itnt);
    		finish();
    	}
    };
    //Recogiendo los que se encuentran.
    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
    	public void onReceive(Context c, Intent i){
    		
    		
    		if (DEBUG) Log.d(TAG, "onReceive");
    		String a = i.getAction();
    		if(BluetoothDevice.ACTION_FOUND.equals(a)){
    			BluetoothDevice d = i.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    			if (d.getBondState() != BluetoothDevice.BOND_BONDED) {
    			mLista.add(d.getName()+"\n"+d.getAddress());
    			}
    		}else{ if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(a)){
    			if(mLista.getCount()==0){
    				mLista.add("No se encontro nada.");
    			}
    		}
    			
    		}
    		
    	}
    };
    protected void onDestroy() {
        super.onDestroy();

        if (DEBUG) Log.d(TAG, "onDestroy");
        if (mBluetoothAdapter != null) {
            mBluetoothAdapter.cancelDiscovery();
        }

        // Unregister broadcast listeners
        this.unregisterReceiver(mBroadcastReceiver);
    }
}